import React, { Component } from "react";
import { Button, Table, Space, message, Tooltip, Tag } from "antd";
import {
  DeleteOutlined,
  DownloadOutlined,
  DeleteFilled
} from "@ant-design/icons";
import "antd/dist/antd.css";
import { queryTask, delById, downloadById } from "../../api2";
import { exportRisk } from "../../api";
// import { getDeptByCode } from "../../utils/index.js";
// import moment from "moment";
// import "moment/locale/zh-cn";
import HasPermi from "../../componentJsx/common/hasPermi";
import NewModal from "../../componentJsx/common/NewModal";
import "../../componentCss/component.css";
// import "./index.css";
//字典
import { getDictionaryLabel } from "../../rudexRou/OperatesCookie.js";
// import { values } from "underscore";
// import { T } from "antd/lib/upload/utils";

class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      tableData: [],
      downloadModalVisible: false, //导出
      confirmLoading: false, //确认按钮异步等待
      loading: false, //表格等待
      total: 0, //分页
      pageSize: 10,
      page: 1,
      downloadModalVisible: false,
      deleteModalVisible: false,
      selectedRowKeys: [], //最新表格多选
      selectedRows: [],
      //表格列
      tableColumns: [
        {
          title: "模块",
          dataIndex: "taskServiceName",
          key: "taskServiceName",
          // fixed: 'left',
          width: 140,
          render: (text) =>
            text ? getDictionaryLabel("taskModule", text) : text,
        },
        {
          title: "任务类型",
          dataIndex: "taskType",
          width: 100,
          key: "taskType",
          render: (text) =>
            text.toString() || text === 0
              ? getDictionaryLabel("taskType", text.toString())
              : text,
        },
        {
          title: "任务开始时间",
          width: 160,
          dataIndex: "taskDate",
          key: "taskDate",
        },
        {
          title: "任务完成时间",
          width: 160,
          dataIndex: "updateDate",
          key: "updateDate",
        },
        {
          title: "导入/导出人",
          width: 120,
          dataIndex: "creatUserEmpName",
          key: "creatUserEmpName",
        },
        {
          title: "导入/导出状态",
          width: 120,
          dataIndex: "taskStatus",
          key: "taskStatus",
          align: "center",
          render: (text) => {
            let color = "";
            switch (text) {
              case 1:
                color = "processing";
                break;
              case 2:
                color = "success";
                break;
              case 3:
                color = "error";
                break;
              case 4:
                color = "warning";
                break;
              default:
                break;
            }
            return (
              <Tag color={color}>{getDictionaryLabel("taskStatus", text)}</Tag>
            );
          },
        },

        {
          title: "操作",
          dataIndex: "handle",
          ellipsis: true,
          width: 140,
          // fixed: 'right',
          align: "center",
          render: (_, record) => (
            <Space>
              <Tooltip title="删除任务记录">
                <Button
                  disabled={record.taskStatus >= 2 ? false : true}
                  danger
                  type="link"
                  onClick={() => {
                    this.showModal("delete", record);
                  }}
                >
                  <DeleteOutlined />
                </Button>
              </Tooltip>
              <Tooltip title="下载文件">
                <Button
                  disabled={
                    record.taskStatus >= 2 && record.filePatch ? false : true
                  }
                  type="link"
                  onClick={() => {
                    this.showModal("download", record);
                  }}
                >
                  <DownloadOutlined />
                </Button>
              </Tooltip>
            </Space>
          ),
        },
      ],
      selectId: null,
      refreshSpin: false,
    };
  }
  onSelectChange = (selectedRowKeys, selectedRows) => {
    this.setState({ selectedRowKeys, selectedRows });
  };
  showModal = (name, record) => {
    if (name == "delete") {
      if (!record && this.state.selectedRowKeys.length == 0) {
        message.warning("请从列表中选择需要删除的任务");
        return;
      }
    }
    this.setState({
      selectId: record,
      deleteModalVisible: name == "delete" ? true : false, //删除的模态框
      downloadModalVisible: name == "download" ? true : false, //导出
    });
  };
  hiddenModal = () => {
    this.setState({
      selectId: null,
      deleteModalVisible: false, //删除的模态框
      downloadModalVisible: false, //导出
      confirmLoading: false, //确认按钮异步等待
    });
  };
  buttonLoading = (flag) => {
    this.setState({ confirmLoading: flag });
  };
  getData = () => {
    this.setState({ loading: true });
    let param = {};
    param.current = this.state.page;
    param.size = this.state.pageSize;
    queryTask(param)
      .then((res) => {
        if (res.data.code === 200) {
          this.setState({
            tableData: res.data.data.records,
            total: res.data.data.total,
            loading: false,
            refreshSpin: false,
          });
        } else {
          message.error(res.data.message || "数据获取失败");
          this.setState({ loading: false, refreshSpin: false });
        }
      })
      .catch((err) => {
        message.error("数据获取失败");
        this.setState({ loading: false, refreshSpin: false });
      });
  };
  downloadFile = () => {
    let timer = null;
    this.setState({
      confirmLoading: true
    });

    let fileName = "";
    if (this.state.selectId.taskType) {
      fileName =
        getDictionaryLabel("taskModule", this.state.selectId.taskServiceName) +
        "导入详情.xlsx";
    } else {
      fileName =
        getDictionaryLabel("taskModule", this.state.selectId.taskServiceName) +
        "导出详情.xlsx";
    }
    downloadById(
      "/tmfs/excelTask/downloadById?id=" + this.state.selectId.id,
      fileName
    ).then((res) => {
      const content = res.data
      const blob = new Blob([content])
      fileName = fileName || '导出数据.xlsx'
      const selfURL = window[window.webkitURL ? 'webkitURL' : 'URL']
      let elink = document.createElement('a')
      if ('download' in elink) {
        elink.download = fileName
        elink.style.display = 'none'
        elink.href = selfURL['createObjectURL'](blob)
        document.body.appendChild(elink)

        // 触发链接
        elink.click()
        selfURL.revokeObjectURL(elink.href)
        document.body.removeChild(elink)
        this.hiddenModal()
        this.setState({
          confirmLoading:false
        })
      } else {
        navigator.msSaveBlob(blob, fileName)
      }
    })
  };
  delById = () => {
    this.buttonLoading(true);
    let ids = [];
    if (this.state.selectId) {
      ids = [this.state.selectId.id];
    } else if (this.state.selectedRowKeys) {
      ids = this.state.selectedRowKeys;
    }
    delById(ids)
      .then((res) => {
        if (res.data.code === 200) {
          message.success("删除成功");
          this.setState({ selectedRowKeys: [], selectedRows: [] });
          this.getData();
          this.hiddenModal();
        } else {
          message.error(res.data.message || "删除失败");
          this.buttonLoading(false);
        }
      })
      .catch((err) => {
        console.log(err);
        message.error("删除失败");
        this.buttonLoading(false);
      });
  };
  changePage = (page, pageSize) => {
    this.setState(
      {
        page,
        pageSize,
      },
      () => {
        this.getData();
      }
    );
  };
  refresh = () => {
    this.setState(
      {
        refreshSpin: true,
      },
      () => this.getData()
    );
  };
  componentWillMount() {
    this.getData();
  }
  componentDidMount() { }
  //组件销毁时取消setState
  componentWillUnmount() {
    this.setState = (state, callback) => {
      return;
    };
  }
  render() {
    const rowSelection = {
      selectedRowKeys: this.state.selectedRowKeys,
      onChange: this.onSelectChange,
    };
    return (
      <div id="evaluate">
        <div className="myProjectsBody">
          <div className="tabstyle">
            <div className="bigContent1" id="projectDetail">
              <div className="operatingDiv">
                <Button
                  onClick={this.refresh}
                  loading={this.state.refreshSpin}
                  type="primary"
                >
                  刷新
                </Button>
                <Button
                  danger
                  onClick={() => this.showModal("delete")}
                  icon={<DeleteOutlined />}
                >
                  删除
                </Button>
              </div>
              <div className="tableDiff">
                <Table
                  rowSelection={{ type: "checkbox", ...rowSelection }}
                  rowKey={(record) => record.id}
                  loading={this.state.loading}
                  style={{ marginTop: 10 }}
                  scroll={{ x: "100" }}
                  columns={this.state.tableColumns}
                  dataSource={this.state.tableData}
                  pagination={{
                    total: this.state.total,
                    pageSize: this.state.pageSize,
                    current: this.state.page,
                    showSizeChanger: true,
                    onChange: this.changePage,
                    showTotal: (total) => "共 " + total + " 条",
                  }}
                  bordered
                />
              </div>
            </div>
          </div>
        </div>
        <NewModal
          modalOptions={{
            width: "400px",
            title: "删除",
            onCancel: this.hiddenModal,
            visible: this.state.deleteModalVisible,
          }}
          buttonOptions={{
            position: "right",
            btnList: [
              {
                key: 1,
                onClick: this.hiddenModal,
                text: "取消",
              },
              {
                key: 0,
                onClick: this.delById,
                text: "确认删除",
                type: "primary",
                loading: this.state.confirmLoading,
              },
            ],
          }}
        >
          <DeleteFilled
            style={{
              fontSize: "28px",
              color: "#e00",
              float: "left",
              backgroundColor: "#f002",
              padding: 8,
              borderRadius: "50%",
            }}
          />
          <div
            style={{
              fontSize: 14,
              marginLeft: 60,
              fontWeight: 700,
              lineHeight: "44px",
              color: "red",
            }}
          >
            任务记录删除后数据不可恢复，请谨慎操作！
          </div>
        </NewModal>
        <NewModal
          modalOptions={{
            width: "400px",
            title: "下载",
            onCancel: this.hiddenModal,
            visible: this.state.downloadModalVisible,
          }}
          buttonOptions={{
            position: "right",
            btnList: [
              {
                key: 1,
                onClick: this.hiddenModal,
                text: "取消",
              },
              {
                key: 0,
                onClick: this.downloadFile,
                text: "确认下载",
                type: "primary",
                loading: this.state.confirmLoading,
              },
            ],
          }}
        >
          确认下载当前文件？
        </NewModal>
      </div>
    );
  }
}
export default Index;
